package com.lungle.warmdiary.app.view.me;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.exception.ApiErrorHelper;
import com.lungle.warmdiary.app.api.exception.ApiException;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.request.PwdResetPost;
import com.lungle.warmdiary.app.ui.InputItemView;
import com.lungle.warmdiary.app.utils.StringUtils;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by God on 2016/8/9.
 */
public class PwdResetActivity extends BaseActivity implements View.OnClickListener {
    private static final String PASSWORD_RESET_SCREEN = "password reset screen";

    public static final int REQUEST_CODE_INIT = 0;
    private static final String BUNDLE_KEY_REQUEST_CODE = "BUNDLE_KEY_REQUEST_CODE";

    private int requestCode = REQUEST_CODE_INIT;

    private EditText mEtPhone;
    private Button mBtnCaptcha;
    private InputItemView mEtCapture;
    private InputItemView mEtNewPwd;
    private InputItemView mNewPwdVerify;
    private Button mBtnSubmit;

    protected int getLayoutId() {
        return R.layout.fragment_pwd_reset;
    }

    @Override
    protected boolean hasActionBar() {
        return true;
    }

    @Override
    protected boolean hasBackButton() {
        return true;
    }

    @Override
    protected int getActionBarTitle() {
        return R.string.pwd_change;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);

        initViews();
    }

    private void initViews() {
        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mBtnCaptcha = (Button) findViewById(R.id.btn_captcha);
        mEtCapture = (InputItemView) findViewById(R.id.et_capture);
        mEtNewPwd = (InputItemView) findViewById(R.id.et_new_pwd);
        mNewPwdVerify = (InputItemView) findViewById(R.id.et_new_pwd_verify);
        mBtnSubmit = (Button) findViewById(R.id.btn_submit);


        mBtnCaptcha.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.btn_captcha:
                getCapture();
                break;
            case R.id.btn_submit:
                String newPwd = mEtNewPwd.getInputText();
                String capture = mEtCapture.getInputText();
                String pwdVerify = mNewPwdVerify.getInputText();
                String phone = mEtPhone.getText().toString();
                if (prepareChange(capture, newPwd, pwdVerify)) {
                    handlSubmit(phone, capture, newPwd);
                }
                break;
        }

    }


    private void getCapture() {
        String phone = mEtPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            AppContext.showToast("手机号为空");
            return;
        }

        if (!StringUtils.isPhone(phone)) {
            AppContext.showToast("非法手机号");
            return;
        }

        showWaitDialog("正在获取...");
        ApiFactory.getBaseApi().getCapture(phone, 2).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(PwdResetActivity.this) {

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                        timer.start();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (e instanceof ApiException) {
                            ApiErrorHelper.showErrorDetail(((ApiException) e).getExtendErrorMsg());
                        }
                        hideWaitDialog();
                    }
                });


    }

    private void handlSubmit(String phone, String capture, String pwd) {
        showWaitDialog("正在修改密码");
        PwdResetPost pwdResetPost = new PwdResetPost(phone, capture, pwd);
        ApiFactory.getBaseApi().resetPwd(pwdResetPost).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(PwdResetActivity.this) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                        AppContext.getInstance().Logout();
                        UIHelper.showLogin(PwdResetActivity.this);
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                        if (e instanceof ApiException) {
                            ApiException exception = (ApiException) e;
                            ApiErrorHelper.showErrorDetail(exception.getExtendErrorMsg());
                        }

                    }
                });


    }

    private boolean prepareChange(String capture, String newPwd, String confirmPwd) {
        if (TextUtils.isEmpty(capture)) {
            mEtCapture.setErrorTip("未填写");
            return false;
        }
        if (checkPassword(newPwd, confirmPwd)) return false;

        return true;
    }

    private boolean checkPassword(String newPwd, String confirmPwd) {
        if (TextUtils.isEmpty(newPwd)) {
            mEtNewPwd.setErrorTip("未填写");
            return true;
        }
        if (newPwd.length() < 6) {
            mEtNewPwd.setErrorTip("输入格式错误");
            return true;
        }
        if (newPwd.length() > 12) {
            mEtNewPwd.setErrorTip("输入格式错误");
            return true;
        }
        if (!StringUtils.isSafePwd(newPwd)) {
            mEtNewPwd.setErrorTip("输入格式错误");
            return true;
        }

        if (TextUtils.isEmpty(confirmPwd)) {
            mNewPwdVerify.setErrorTip("未填写");
            return true;
        }

        if (!newPwd.equals(confirmPwd)) {
            mNewPwdVerify.setErrorTip("密码不一致");
            return true;
        }
        return false;
    }


    private void handleChangeSuccess() {
        Intent data = new Intent();
        data.putExtra(BUNDLE_KEY_REQUEST_CODE, requestCode);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(PASSWORD_RESET_SCREEN);
        MobclickAgent.onResume(this);

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(PASSWORD_RESET_SCREEN);
        MobclickAgent.onPause(this);

    }


    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mBtnCaptcha.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            mBtnCaptcha.setText(millisUntilFinished / 1000 + "秒后\n重新获取");
            mBtnCaptcha.setClickable(true);
            mBtnCaptcha.setEnabled(false);
        }

        @Override
        public void onFinish() {
            mBtnCaptcha.setClickable(true);
            mBtnCaptcha.setEnabled(true);
            mBtnCaptcha.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            mBtnCaptcha.setText("获取验证码");
        }
    };
}
